package com.haoyeteng.sxbd.modular.business.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.haoyeteng.sxbd.core.base.controller.BaseController;
import com.haoyeteng.sxbd.core.common.constant.factory.ConstantFactory;
import com.haoyeteng.sxbd.core.common.constant.factory.PageFactory;
import com.haoyeteng.sxbd.core.constant.SxbdConstants;
import com.haoyeteng.sxbd.core.exception.SxbdException;
import com.haoyeteng.sxbd.core.util.DateUtil;
import com.haoyeteng.sxbd.core.util.ExportExcelUtils;
import com.haoyeteng.sxbd.core.util.ToolUtil;
import com.haoyeteng.sxbd.modular.business.model.OrderDtl;
import com.haoyeteng.sxbd.modular.business.service.IOrderDtlService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.haoyeteng.sxbd.core.base.model.ResponseResult;
import com.haoyeteng.sxbd.core.common.annotion.Permission;

import java.io.OutputStream;
import java.lang.reflect.Array;
import java.net.URLEncoder;
import java.util.*;

import com.haoyeteng.sxbd.core.log.LogObjectHolder;
import com.haoyeteng.sxbd.modular.business.model.Order;
import com.haoyeteng.sxbd.modular.business.service.IOrderService;

import javax.servlet.http.HttpServletResponse;

/**
 * 订单表控制器
 *
 * @author haoyeteng
 * @date 2019-06-27 01:03:55
 */
@Controller
@RequestMapping("/order")
public class OrderController extends BaseController {

    private static final String PREFIX = "/business/order/";

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderDtlService orderDtlService;



    /**
     * 跳转到订单表首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "order.html";
    }

    /**
     * 跳转到添加订单表
     */
//    @RequestMapping("/order_add")
//    public String orderAdd() {
//        return PREFIX + "order_add.html";
//    }

    /**
     * 跳转到修改订单表
     */
//    @RequestMapping("/order_update/{orderId}")
//    public String orderUpdate(@PathVariable Integer orderId, Model model) {
//        Order order = orderService.selectById(orderId);
//        model.addAttribute("item",order);
//        LogObjectHolder.me().set(order);
//        return PREFIX + "order_edit.html";
//    }

    /**
     * 获取订单表列表
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ResponseBody
    @Permission
    public ResponseResult<Object> list(Integer payState,Integer payType,String startDate,String endDate
            ,String orderId,String userName,String swiftNo) {
        Page<Order> page = new PageFactory<Order>().defaultPage();
        Map<String, Object> params = new HashMap<>(16);
        params.put("payState", payState);
        params.put("payType", payType);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("orderId", orderId);
        params.put("userName", userName);
        params.put("swiftNo", swiftNo);
        //订单分页查询
    	List<Map<String, Object>> orders = orderService.selectOrders(page,params);
        ResponseResult<Object> result = new ResponseResult<Object>();
        result.setData(orders);
 		result.setCount(page.getTotal());
     	result.setCode(SUCCESS_TIP.getCode());
     	result.setMsg(SUCCESS_TIP.getMessage());
 		return result;
    }

    /**
     * 导出订单
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    @Permission
    public Object export(HttpServletResponse response, Integer payState,Integer payType,String startDate,String endDate
            ,String orderId,String userName,String swiftNo) throws Exception{
        Map<String, Object> params = new HashMap<>(16);
        params.put("payState", payState);
        params.put("payType", payType);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("orderId", orderId);
        params.put("userName", userName);
        params.put("swiftNo", swiftNo);
        List<Map<String, Object>> ordersList = orderService.selectOrdersList(params);

        List<List<String>> orderData = new ArrayList<List<String>>();
        if (ToolUtil.isNotEmpty(ordersList)) {
            for (Map<String,Object> orderMap : ordersList){
                List<String> rowList = new ArrayList<>();
                rowList.add(getString(orderMap.get("orderId")));
                rowList.add(getString(orderMap.get("userName")));
                rowList.add(ToolUtil.isEmpty(orderMap.get("createTime")) ? "" : DateUtil.getTime((Date) orderMap.get("createTime")));
                rowList.add(ToolUtil.isEmpty(orderMap.get("payType")) ? ""
                        : (SxbdConstants.ORDER_PAY_TYPE_ALIPAY.equals(orderMap.get("payType")) ? "支付宝"
                        : (SxbdConstants.ORDER_PAY_TYPE_WECHAT.equals(orderMap.get("payType")) ? "微信"
                        : (SxbdConstants.ORDER_PAY_TYPE_BANK_TRANSFER.equals(orderMap.get("payType")) ? "银行转账" : ""))));
                rowList.add(getString(orderMap.get("swiftNo")));
                rowList.add(ToolUtil.isEmpty(orderMap.get("payState")) ? ""
                        : (SxbdConstants.ORDER_PAY_STATE_NOPAY.equals(orderMap.get("payState")) ? "待支付"
                        : (SxbdConstants.ORDER_PAY_STATE_PAYMENTED.equals(orderMap.get("payState")) ? "已支付" : "")));
                rowList.add(getString(orderMap.get("orderPrice")));
                orderData.add(rowList);
            }
        }

        //表名
        String fileName ="订单信息表"+DateUtil.getAllTime();
        // 第六步，将文件存到浏览器设置的下载位置
        String filename = fileName + ".xls";

        response.setContentType("application/ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename="
                .concat(String.valueOf(URLEncoder.encode(filename, "UTF-8"))));
        OutputStream out = response.getOutputStream();
        ExportExcelUtils eeu = new ExportExcelUtils();
        HSSFWorkbook workbook = new HSSFWorkbook();

        String[] header = {"订单号", "用户名", "创建时间", "支付方式", "汇款凭证号", "支付状态", "订单金额"};
        Integer sheetNum = 0;
        eeu.exportExcel(workbook, sheetNum, "订单信息", header, orderData, out);
        try {
            // 将数据写出去
            workbook.write(out);
            String str = "导出" + fileName + "成功！";
            System.out.println(str);
        } catch (Exception e) {
            e.printStackTrace();
            String str1 = "导出" + fileName + "失败！";
            System.out.println(str1);
        } finally {
            out.close();
        }
        return SUCCESS_TIP;
    }
    /**
     * 新增订单表
     */
//    @RequestMapping(value = "/add")
//    @ResponseBody
//    @Permission
//    public Object add(Order order) {
//        orderService.insert(order);
//        return SUCCESS_TIP;
//    }

    /**
     * 删除订单表
     */
//    @RequestMapping(value = "/delete")
//    @ResponseBody
//    @Permission
//    public Object delete(@RequestParam Integer orderId) {
//        orderService.deleteById(orderId);
//        return SUCCESS_TIP;
//    }

    /**
     * 修改订单表 1.修改支付状态为已支付 2.生成差分账号
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    @Permission
    public Object update(Order order) {
        //校验
        Order orderAndDtl = orderService.selectOrderAndDtlById(order.getOrderId());
        if (ToolUtil.isEmpty(orderAndDtl)){
            throw new SxbdException("订单不存在！");
        }
        if (!SxbdConstants.ORDER_PAY_STATE_NOPAY.equals(orderAndDtl.getPayState())){
            throw new SxbdException("订单Id:" + order.getOrderId() + "不是待支付状态!");
        }
        if (ToolUtil.isEmpty(orderAndDtl.getDetails())){
            throw new SxbdException("获取订单Id:" + order.getOrderId() + "明细信息失败!");
        }
        boolean flag = orderService.updateAndSaveAccount(orderAndDtl);
        if(flag) {
        	ConstantFactory.me().toSendUserMsg("USER_SERVICE", "您已成功支付"+orderAndDtl.getOrderId()+"订单！若购买服务包含厘米级定位（RTK），为保证服务正常使用，请在服务管理页面中及时上传设备！", orderAndDtl.getUserId());
        }
        return SUCCESS_TIP;
    }

    /**
     * 订单表详情
     */
    @RequestMapping(value = "/detail/{orderId}")
    public Object detail(Model model, @PathVariable("orderId") String orderId) {
        Order order = orderService.selectOrderAndDtlById(orderId);
        model.addAttribute("item", order);
        return PREFIX + "order_detail.html";
    }

    /**
     * 取消订单 删除订单及明细
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam String orderId) {
        //删除订单及明细
        orderService.deleteOrderAndDtlById(orderId);
        return SUCCESS_TIP;
    }

    /**
     * 获取字符串类型数据
     * @param o object
     * @return 字符串类型数据
     */
    private String getString(Object o){
        return ToolUtil.isEmpty(o) ? "" : o.toString();
    }
}
